import React, { memo, useRef, FC } from 'react';
import { FormInstance } from 'antd/lib/form';
// import styles from './index.less';
import CommonModal from '@/components/CommonModal';
import AddForm from './AddForm';
import { modelName } from '@/pages/Users';
import useHoxModel from '@/pages/Users/useHoxModel';
import { ActionType } from '@/components/ProTable';
import { AddUserTypeReturnType } from '@/pages/Users/API';

interface Props {
  actionRef: React.MutableRefObject<ActionType | undefined>;
}

const ModalContent: FC<Props> = (props) => {
  const { actionRef } = props;
  const { addUser, editUser, userInfo } = useHoxModel((model) => [model.addUser, model.userInfo]);
  const photoRef = useRef<FormInstance>();
  const rightRef = useRef<FormInstance>();
  const bottomRef = useRef<FormInstance>();

  const confim = async <T extends {}>(
    cancel: () => void,
    request: (params: T) => Promise<any>,
    otherData: { id?: number } = {},
  ) => {
    try {
      const photoFields: any = await photoRef.current?.validateFields();
      const rightFields: any = await rightRef.current?.validateFields();
      const bottomFields: any = await bottomRef.current?.validateFields();

      let res = await request({ ...bottomFields, ...rightFields, ...photoFields, ...otherData });
      if (!(res.result < 0)) {
        actionRef.current?.reloadAndRest();
        cancel();
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  };
  return (
    <>
      <CommonModal
        title="编辑"
        width={600}
        type={modelName + 'edit'}
        onOk={async (cancelModal: (type?: string, clear?: boolean) => void) => {
          await confim<AddUserTypeReturnType>(cancelModal, editUser, { id: userInfo.id });
        }}
      >
        <AddForm rightRef={rightRef} isEdit bottomRef={bottomRef} photoRef={photoRef} />
      </CommonModal>
      <CommonModal
        title="新增"
        width={600}
        type={modelName + 'add'}
        onOk={async (cancelModal: (type?: string, clear?: boolean) => void) => {
          await confim<AddUserTypeReturnType>(cancelModal, addUser);
        }}
      >
        <AddForm rightRef={rightRef} bottomRef={bottomRef} photoRef={photoRef} />
      </CommonModal>
    </>
  );
};

export default memo(ModalContent);
